﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using PSE.Framework.Configuration;
using PSE.LogPackager.Common.Configuration;
using System.ServiceModel.Channels;
using PSE.LogPackager.Common.Service;

namespace PSE.LogPackager.Service
{
    public class LogPackagerServiceHost
    {
        private static ServiceHost _host;

        public static void Start(SystemComponent component)
        {
            if (_host != null && _host.State == CommunicationState.Opened)
                throw new Exception("Log Packager Service host is already opened.");

            ApplicationConfiguration applicationConfiguration = PSE.Framework.Configuration.ApplicationConfiguration.GetCurrent();
            LogPackagerConfigurationSection logPackagerConfiguration = applicationConfiguration.GetSection<LogPackagerConfigurationSection>("logPackagerConfiguration");

            Uri address = logPackagerConfiguration.GetAddress(component.Name);
            Binding binding = logPackagerConfiguration.GetBinding(address);

            _host = new ServiceHost(typeof(LogPackagerService));
            _host.AddServiceEndpoint(typeof(ILogPackagerService), binding, address);
            _host.Open();
        }

        public static void Stop()
        {
            if (_host != null && _host.State == CommunicationState.Opened)
            {
                try
                {
                    _host.Close();
                }
                catch
                {
                    _host.Abort();
                }

                _host = null;
            }
        }
    }
}
